package com.qiguliuxing.dts.admin.dao;



import com.alibaba.excel.EasyExcel;
import com.qiguliuxing.dts.admin.dao.dto.WeekRange;
import com.qiguliuxing.dts.admin.web.AdminIordersController;
import com.qiguliuxing.dts.db.domain.Iorders;
import io.swagger.models.auth.In;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.channels.FileChannel;
import java.text.DecimalFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class IorderSpecial {
    private static final Logger logger = LoggerFactory.getLogger(AdminIordersController.class);
    public static String getPackType(String deliveryType, Integer orderCount) {
        String packType = "";
        if (deliveryType.equals("空运") || deliveryType.equals("汽运")) {
            if (orderCount < 20) {
                packType = "空-E";
            } else {
                packType = "空-C";
            }
        } else if (deliveryType.equals("铁运")) {
            if (orderCount < 30) {
                packType = "铁-E";
            } else if (orderCount >= 30) {
                packType = "铁-C";
            }
        } else {

        }

        return packType;
    }

    public static String getCF(Integer orderCount) {
        String CF = "";
        if (orderCount < 20) {
            CF = "国药准字H10983122";
        } else if (orderCount >= 20 && orderCount < 50) {
            CF = "国药准字H10983122";
        } else if (orderCount >= 50 && orderCount < 100) {
            CF = "国药准字H10983119";
        } else if (orderCount >= 100 && orderCount < 200) {
            CF = "国药准字H10983120";
        } else if (orderCount >= 200) {
            CF = "国药准字H10983121";
        }


        return CF;
    }

    public static Double getTransIndex(Integer orderCount) {
        Double index = 0.0;
        if (orderCount < 100) {
            index = 0.1;
        } else if (orderCount >= 100 && orderCount < 250) {
            index = 0.2;
        } else if (orderCount == 250) {
            index = 0.3;
        } else if (orderCount > 250 && orderCount < 500) {
            index = 0.4;
        } else if (orderCount == 500) {
            index = 0.5;
        } else if (orderCount > 500 && orderCount < 800) {
            index = 0.6;
        } else if (orderCount >= 800 && orderCount < 950) {
            index = 0.7;
        } else if (orderCount >= 950 && orderCount < 1500) {
            index = 0.8;
        } else {
            index = 0.8;
        }

        return index;
    }

    public static Integer getPackIndex() {
        Integer packIndex = 0;


        return packIndex;

    }

    //获取包装量基数
    public static Double getPackIndex(Integer orderCount, String deliveryType, Double splitCount) {//三个参数：订量、发货方式、计算量
        Double packIndex = 0.0;
        DecimalFormat decimalFormat2 = new DecimalFormat("#0.0");
        if (deliveryType.equals("空运") || deliveryType.equals("汽运")) {
            if (splitCount <= 10) {
                packIndex = 1.0;
            } else if (splitCount > 10 && orderCount <= 20000) {
                packIndex = Double.valueOf(decimalFormat2.format(splitCount / 10));
            }
        } else if (deliveryType.equals("铁运")) {
            if (orderCount <= 500) {
                packIndex = 1.0;
            } else if (orderCount > 500 && orderCount <= 1000) {
                packIndex = 2.0;
            } else if (orderCount > 1000) {
                packIndex = Double.valueOf(decimalFormat2.format(orderCount / 500));
            }
        }


        return packIndex;

    }

    public static Double getResult(String res) {
        Double res2 = 0.00;
        if (res.equals("广东希埃医药有限公司")) {
            res2 = 1.10;
        } else if (res.equals("成都市第五人民医院")) {
            res2 = 1.03;
        } else {
            res2 = 1.05;
        }
        return res2;
    }


    public static String getType(Integer orderCount) {
        String type = "";
        if (orderCount < 50) {
            type = "925Mbq";
        } else if (orderCount >= 50 && orderCount < 100) {
            type = "1850Mbq";
        } else if (orderCount >= 100 && orderCount < 200) {
            type = "3700Mbq";
        } else if (orderCount >= 200) {
            type = "7400Mbq";
        }
        return type;
    }

    public static Iorders getIorders(List<IordersTemplate> list) {
        Iorders iorder = new Iorders();
        String date;
        DecimalFormat decimalFormat = new DecimalFormat("#0.00");
        Double orderCount1 = 0.00;//空运总订量
        Double orderCount2 = 0.00;//汽运总订量
        Double orderCount3 = 0.00;//铁运总订量
        Integer countDrumA = 0;//A型桶
        Integer countDrumB = 0;//B型桶
        Integer countDrumC = 0;//C型桶
        Integer countLeadC = 0;//C型铅罐
        Integer countLeadB = 0;//B型铅罐
        Integer countLeadE = 0;//E型铅罐
        Integer piecesTotal = 0;//总件数
        String batchNumber = "";
        Double splitVolumeCount = 0.00;
        Integer activity = 0;//测量活度
        String measureTime;
        Double totalActivity = 0.00;
        Double productionQuantity = 0.00;//生产量
        Double remainQuantity = 0.00;
        Double remainActivity = 0.00;
        Double sodiumHippurate = 0.00;//邻碘马尿酸钠分装量
        for (IordersTemplate it : list) {
            splitVolumeCount = splitVolumeCount + Double.valueOf(it.getSplitQuantity());
            if (IorderSpecial.getPackType(it.getDeliveryType(), Integer.valueOf(it.getOrderCount())) == "空-C") {
                countDrumA = countDrumA + it.getPieces();
                countLeadC = countLeadC + it.getPieces();
            }
            ;
            if (IorderSpecial.getPackType(it.getDeliveryType(), Integer.valueOf(it.getOrderCount())) == "铁-C") {
                countLeadC = countLeadC + it.getPieces();
                countDrumC = countDrumC + it.getPieces();
            }
            ;
            if (IorderSpecial.getPackType(it.getDeliveryType(), Integer.valueOf(it.getOrderCount())) == "空-E") {
                countLeadE = countLeadE + it.getPieces();
                countDrumB = countDrumB + it.getPieces();
            }

                if (IorderSpecial.getPackType(it.getDeliveryType(), Integer.valueOf(it.getOrderCount())) == "铁-B") {
                    countLeadB = countLeadB + it.getPieces();
                    countDrumA = countDrumA + it.getPieces();
                }
                ;
                if (IorderSpecial.getPackType(it.getDeliveryType(), Integer.valueOf(it.getOrderCount())) == "空-B") {
                    countLeadB = countLeadB + it.getPieces();
                    countDrumA = countDrumA + it.getPieces();
                }
                ;
                piecesTotal = piecesTotal + it.getPieces();
                batchNumber = it.getMaterialBatch();
                measureTime = it.getMeasureTime();
                if(it.getMeasureTime().length()>12) {
                    iorder.setMeasureTime(LocalDateTime.parse(measureTime));
                }else{
                    iorder.setMeasureTime(LocalDate.parse(measureTime).atTime(12, 0));
                }

                iorder.setBatchNumber(batchNumber);
                totalActivity = totalActivity + Double.valueOf(it.getActualCount()) * it.getPieces();
                if (it.getDeliveryType().equals("空运")) {

                    orderCount1 = orderCount1 + Double.valueOf(it.getOrderCount());
                } else if (it.getDeliveryType().equals("铁运")) {
                    orderCount2 = orderCount2 + Double.valueOf(it.getOrderCount());
                } else {
                    orderCount3 = orderCount3 + Double.valueOf(it.getOrderCount());
                }

            }
            iorder.setDrumA(countDrumA);
            iorder.setDrumB(countDrumB);
            iorder.setDrumC(countDrumC);
            iorder.setLeadB(countLeadB);
            iorder.setLeadC(countLeadC);
            iorder.setLeadE(countLeadE);
            iorder.setOrderCount1(Double.valueOf(decimalFormat.format(orderCount1 / 1000)));
            iorder.setOrderCount2(Double.valueOf(decimalFormat.format(orderCount2 / 1000)));
            iorder.setOrderCount3(Double.valueOf(decimalFormat.format(orderCount3 / 1000)));
            iorder.setPieces(piecesTotal);
            iorder.setSplitActivity(Double.valueOf(decimalFormat.format(totalActivity / 1000)));
            iorder.setSplitVolume(splitVolumeCount);
            return iorder;
        }
        //此函数用来判断文件夹中分装清单情况，生成的分装清单，若当日已有，则将其是第几个的序号生成在文件名里面。
        public static String createSplitFile(){ //依次传入项目条数、取样体积、留样体积三个参数
            String returnFileName="";
            File folder = new File("D:/1--碘－131计算程序/计算结果/2025年分装清单/"); // 指定目录路径
            DecimalFormat decimalFormat2 = new DecimalFormat("YYYY-MM-dd");

            String todayDate=LocalDate.now().toString();// 表示今天的分装清单
           /* String searchString = "yourSearchString"; */
            boolean found = false;
            Integer index=1;
            File[] listOfFiles = folder.listFiles();

            if (listOfFiles != null) {
                for (File file : listOfFiles) {
                    if (file.isFile() && file.getName().contains(todayDate)) {
                        found = true;
                        index=index+1;
                        /*break; // 找到第一个匹配的文件后即可退出循环*/
                    }
                }
            }
            String sourcePath = "D:/1--碘－131计算程序/模版/产品分装清单模板.xlsx";
            String targetFolder = "D:/1--碘－131计算程序/计算结果/2025年分装清单/";
            String targetPath = targetFolder + "/" +todayDate+"分装清单"+index+".xlsx";


                try (FileInputStream fis = new FileInputStream(sourcePath);

                     XSSFWorkbook workbook = new XSSFWorkbook(fis);
                     FileOutputStream fos = new FileOutputStream(targetPath)) {

                    workbook.write(fos); // 将工作簿写入输出流，即复制到目标路径
                } catch (IOException e) {
                    e.printStackTrace();
                }
               /* try (FileChannel sourceChannel = new FileInputStream(sourcePath).getChannel();
                     FileChannel destChannel = new FileOutputStream(targetPath).getChannel()) {
                    destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
                } catch (IOException e) {
                    e.printStackTrace();
                }*/



            /*if (found) {
                System.out.println("文件存在。");
            } else {
                System.out.println("文件不存在。");
            }*/
            returnFileName=targetPath;


        return  returnFileName;

    }
    public static List<WeekRange> getYearDates(LocalDate startDate, LocalDate endDate) {
        int startYear=startDate.getYear();
        int endYear=endDate.getYear();
        List<WeekRange> weekRanges=new ArrayList<>();
        for(int year=startYear;year<=endYear;year++){
            LocalDate std=LocalDate.of(year,1,1);
            LocalDate end=LocalDate.of(year,12,31);
            WeekRange weekRange=new WeekRange(std,end);
            weekRanges.add(weekRange);
        }


        return weekRanges;
    }

        public static List<WeekRange> getMonthDates(LocalDate startDate, LocalDate endDate) {
            // 定义日期范围


            // 创建一个LinkedHashMap来存储结果，保持插入顺序
            Map<String, String> monthDates = new LinkedHashMap<>();

            List<WeekRange> weekRanges=new ArrayList<>();
            // 遍历日期范围中的每个月
            YearMonth currentMonth = YearMonth.from(startDate);
            while (currentMonth.atEndOfMonth().isBefore(endDate) || currentMonth.atEndOfMonth().isEqual(endDate)) {
                // 获取每月的第一天和最后一天
                LocalDate firstDayOfMonth = currentMonth.atDay(1);
                LocalDate lastDayOfMonth = currentMonth.atEndOfMonth();

                // 将日期格式化为字符串并存储在Map中
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

                WeekRange weekRange=new WeekRange(firstDayOfMonth,lastDayOfMonth);
                /*monthDates.put(formatter.format(firstDayOfMonth), formatter.format(lastDayOfMonth));*/
                weekRanges.add(weekRange);
                // 移动到下一个月
                currentMonth = currentMonth.plusMonths(1);
            }

            return weekRanges;
            // 打印结果


        }

    public static int getDay(String date){
        int year=Integer.valueOf(date.substring(0,4));
        int month=Integer.valueOf(date.substring(5,6));
        int day=Integer.valueOf(date.substring(7,8));

        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, day);  // 使用具体的年、月、日（月份要减1）
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        System.out.println(dayOfWeek);
        return dayOfWeek;
    }

    public static String createShipAccordFile(){ //依次传入项目条数、取样体积、留样体积三个参数
        String returnFileName="";
        File folder = new File("D:/1--碘－131计算程序/计算结果/2025年发运记录/"); // 指定目录路径
        DecimalFormat decimalFormat2 = new DecimalFormat("YYYY-MM-dd");

        String todayDate=LocalDate.now().toString();// 表示今天的分装清单
        /* String searchString = "yourSearchString"; */
        boolean found = false;
        Integer index=1;
        File[] listOfFiles = folder.listFiles();

        if (listOfFiles != null) {
            for (File file : listOfFiles) {
                if (file.isFile() && file.getName().contains(todayDate)) {
                    found = true;
                    index=index+1;
                    /*break; // 找到第一个匹配的文件后即可退出循环*/
                }
            }
        }
        String sourcePath = "D:/1--碘－131计算程序/模版/发运记录模板.xlsx";
        String targetFolder = "D:/1--碘－131计算程序/计算结果/2025年发运记录";
        String targetPath = targetFolder + "/" +todayDate+"发运记录"+index+".xlsx";


        try (FileInputStream fis = new FileInputStream(sourcePath);

             XSSFWorkbook workbook = new XSSFWorkbook(fis);
             FileOutputStream fos = new FileOutputStream(targetPath)) {

            workbook.write(fos); // 将工作簿写入输出流，即复制到目标路径
        } catch (IOException e) {
            e.printStackTrace();
        }
               /* try (FileChannel sourceChannel = new FileInputStream(sourcePath).getChannel();
                     FileChannel destChannel = new FileOutputStream(targetPath).getChannel()) {
                    destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
                } catch (IOException e) {
                    e.printStackTrace();
                }*/



            /*if (found) {
                System.out.println("文件存在。");
            } else {
                System.out.println("文件不存在。");
            }*/
        returnFileName=targetPath;


        return  returnFileName;

    }
    public static int findAndAddMissingNaturalNumber(List<Integer> list) {
        ListIterator<Integer> iterator = list.listIterator();
        int currentNumber = 1; // 从1开始查找缺失的数
        while (iterator.hasNext()) {
            if (iterator.next() != currentNumber) { // 如果当前数不匹配，则找到缺失的数并添加到列表中
                list.add(currentNumber); // 在正确位置插入缺失的数，保持顺序正确
                return currentNumber; // 返回新添加的数字
            }
            currentNumber++; // 移动到下一个应该检查的数
        }
        // 如果所有数字都在列表中，添加最后一个缺失的数（理论上不会执行到这里，除非有逻辑错误）
        list.add(currentNumber); // 理论上不会执行到这里，除非有逻辑错误或故意设计为最后一个缺失的数大于当前检查的最大数。
        return currentNumber; // 返回最后一个应该添加的数字（理论上不会执行到这里）
    }

    //获取某段日期中所有的周。
    public static List<WeekRange> getWeeksBetween(LocalDate startDate, LocalDate endDate) {
        List<WeekRange> weekRanges = new ArrayList<>();
        LocalDate currentDate = startDate;
        while (currentDate.isBefore(endDate) || currentDate.isEqual(endDate)) {
            LocalDate weekStart = currentDate;
            while (weekStart.getDayOfWeek()!= DayOfWeek.MONDAY) {
                weekStart = weekStart.minusDays(1);
            }
            LocalDate weekEnd = weekStart.plusDays(6);
            if (weekEnd.isAfter(endDate)) {
                weekEnd = endDate;
            }
            weekRanges.add(new WeekRange(weekStart, weekEnd));
            currentDate = weekEnd.plusDays(1);
        }
        return weekRanges;
    }
    //判断某天是否在某周内，包括起始日
    public static boolean isDateInWeek(LocalDate dateToCheck, LocalDate startOfWeek, LocalDate endOfWeek) {
        // 将开始日期调整为周一（一周的开始）
        LocalDate adjustedStartOfWeek = startOfWeek.with(DayOfWeek.MONDAY);
        // 将结束日期调整为周日（一周的结束，包含这一天）
        LocalDate adjustedEndOfWeek = endOfWeek.with(DayOfWeek.SUNDAY);

        // 检查日期是否在调整后的日期范围内
        return !dateToCheck.isBefore(adjustedStartOfWeek) && !dateToCheck.isAfter(adjustedEndOfWeek);
    }



    public static Integer findNextNaturalNumber(List<Integer> list) {
        if (list.isEmpty()) {
            return Integer.valueOf(1); // 如果列表为空，返回1作为第一个元素
        }

        Set<Integer> numberSet = new HashSet<>(list); // 使用HashSet存储所有数字，以提高查找效率
        Integer max = list.get(0); // 初始化最大值为列表的第一个元素
        for (Integer num : list) {
            if(num!=null) {
                if (num > max) {
                    max = num; // 找到更大的数并更新最大值
                }
            }
        }

        // 检查下一个自然数是否已在列表中（通过HashSet）
        for (int i = max + 1; ; i++) { // 从max+1开始检查每一个数
            if (!numberSet.contains(Integer.valueOf(i))) { // 如果HashSet中不包含该数，返回它
                return Integer.valueOf(i);
            }
        }
    }
    }